﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Speech.Recognition;
using System.IO;
using System.Speech.AudioFormat;

namespace ClickRead
{
  public class SpeechRecognitionHelper
  {
    public bool Completed { get; set; }
    public string Error { get; set; }
    public bool Canceled { get; set; }
    public bool InputStreamEnded { get; set; }
    public RecognitionResult Result { get; set; }
    public void SpeechToText(Stream audioStream)
    {
      using (SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine())
      {
        // Create and load a grammar.
        Grammar dictation = new DictationGrammar();
        dictation.Name = "Dictation Grammar";
        recognizer.LoadGrammar(dictation);

        // Configure the input to the recognizer.
        recognizer.SetInputToAudioStream(audioStream, new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Mono));

        // Attach event handlers for the results of recognition.
        recognizer.SpeechRecognized +=
          new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
        recognizer.RecognizeCompleted +=
          new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);

        // Perform recognition on the entire file.
        this.Completed = false;
        recognizer.RecognizeAsync();

        // Keep the console window open.
        while (!this.Completed)
        {
          
        }
      }
    }

    // Handle the SpeechRecognized event.
    void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
    {
      if (e.Result != null && e.Result.Text != null)
      {
        this.Result = e.Result;
      }
      else
      {
        this.Error = "Recognized text not available.";
      }
    }

    // Handle the RecognizeCompleted event.
    void recognizer_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)
    {
      if (e.Error != null)
      {
       this.Error = string.Format("Error encountered, {0}: {1}", e.Error.GetType().Name, e.Error.Message);
      }
      if (e.Cancelled)
      {
        this.Canceled = true;
      }
      if (e.InputStreamEnded)
      {
        this.InputStreamEnded = true;
      }
      this.Completed = true;
    }
  }

  public class RecognitionResultJson
  {
    public List<string> Alternates { get; set; }
  }
}